package login

import (
	"github.com/gofiber/fiber/v2"
	businessError "sg-backend/error"
	"sg-backend/global"
	"sg-backend/model/user"
	"strings"
	"time"
)

func OutLogin(ctx *fiber.Ctx) error {

	// 获取用户Token
	authorization := string(ctx.Request().Header.Peek(fiber.HeaderAuthorization))
	authArr := strings.Split(authorization, " ")
	if len(authArr) != 2 || authArr[0] != "Bearer" {
		panic(businessError.New(businessError.TOKEN_NOT_EXISTS))
	}
	tokenString := authArr[1]

	// 从系统中标记token过期
	tokenObj := user.Token{}
	r := global.DB.Where("token = ?", tokenString).First(&tokenObj)
	if r.Error != nil {
		return ctx.JSON(fiber.Map{
			"status":  "error",
			"message": "Token获取失败！",
		})
	}

	// 标记token过期
	tokenObj.ExpireTime = time.Now()
	sr := global.DB.Save(&tokenObj)
	if sr.Error != nil {
		return ctx.JSON(fiber.Map{
			"status":  "error",
			"message": "标记Token过期时间到数据库失败！",
		})
	}

	return ctx.JSON(fiber.Map{
		"status":  "done",
		"message": "退出成功！",
	})
}
